import React, { useEffect, useRef, useState } from 'react'
import { Card, Button, Form, Input, Select, message } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { useHistory } from 'react-router-dom'
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { saveCategoryListAction } from '../../store/actionCreators/admin'
import PicturesWall from './picture_wall'
import RichText from './rich_text'
import ajax from '../../service/ajax'

const { Item } = Form
const { Option } = Select

export default function Add_Update(props) {
  const [isUpdate, setIsUpdate] = useState(false)
  const history = useHistory()
  const dispatch = useDispatch()
  const { categoryList } = useSelector((state) => ({
    categoryList: state.adminInfo.categoryList
  }), shallowEqual)

  const [form] = Form.useForm();

  const id = props.match.params.id

  const picWallRef = useRef()
  const richTextRef = useRef()

  useEffect(() => {
    if (id) {
      setIsUpdate(true)
      getProductDetai(id)
    }
  }, [])

  // 用来判断是否有分类信息
  useEffect(() => {
    if (categoryList.length === 0) {
      dispatch(saveCategoryListAction())
    }
  }, [])

  const getProductDetai = async (id) => {
    let { status, data, msg } = await ajax('/manage/product/info', { params: { productId: id } })
    form.setFieldsValue(data)
    picWallRef.current.setImgs(data.imgs)
    richTextRef.current.setRichText(data.detail)
    console.log(data)
    // console.log(form)
  }

  const onFinish = async (values) => {
    values.detail = richTextRef.current.getRichText()
    values.imgs = picWallRef.current.getImgs()
    let result
    if (isUpdate) {
      values._id = id
      result = await ajax.post('/manage/product/update', values)
    } else {
      result = await ajax.post('/manage/product/add', values)
    }

    let { status, msg } = result

    if (status === 0) {
      message.success(isUpdate ? '修改商品成功' : '添加商品成功')
      history.replace('/admin/prod_about/product')
    } else {
      message.error(msg)
    }
  }

  const getCategoryName = () => {
    return categoryList.map((item) => {
      return <Option key={item._id} value={item._id}>{item.name}</Option>
    })
  }

  return (
    <Card
      title={
        <div>
          <Button
            type="link"
            onClick={() => history.go(-1)}
          >
            <ArrowLeftOutlined />
          返回
        </Button>
          <span>{isUpdate ? '修改商品' : '添加商品'}</span>
        </div>
      }
    >
      <Form
        form={form}
        onFinish={onFinish}
        initialValues={{categoryId:''}}
      >
        <Item
          name="name"
          label="商品名称"
          wrapperCol={{ span: 10 }}
          rules={[
            {
              required: true,
              message: "商品名称不能为空"
            }
          ]}
        >
          <Input placeholder='商品名称' />
        </Item>
        <Item
          name="desc"
          label="商品描述"
          wrapperCol={{ span: 10 }}
          rules={[
            {
              required: true,
              message: "商品描述不能为空"
            }
          ]}
        >
          <Input placeholder="商品描述" />
        </Item>
        <Item
          name="price"
          label="商品价格"
          wrapperCol={{ span: 10 }}
          rules={[
            {
              required: true,
              message: "商品价格不能为空"
            }
          ]}
        >
          <Input
            addonAfter="元"
            addonBefore="￥"
            type="number"
            placeholder="商品价格"
          />
        </Item>
        <Item
          name="categoryId"
          label="商品分类"
          wrapperCol={{ span: 10 }}
          rules={[
            {
              required: true,
              message: "请选择一个分类"
            }
          ]}
        >
          <Select>
            <Option value="">请选择分类</Option>
            {getCategoryName()}
          </Select>
        </Item>
        <Item
          style={{ marginLeft: 10 }}
          label="上传图片"
        >
          <PicturesWall ref={picWallRef} />
        </Item>
        <Item
          label="商品详情"
          wrapperCol={{ span: 20 }}
          style={{ marginLeft: 10 }}
        >
          <RichText ref={richTextRef} />
        </Item>
        <Item>
          <Button htmlType="submit" type="primary">提交</Button>
        </Item>
      </Form>
    </Card>
  )
}